#!/usr/bin/env bash
# Copyright (c) 2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

__patch_stat() {
    awk '
    BEGIN {
        old_file = ""
        new_file = ""
        dels = adds = 0
        files = 0
        insertions = deletions = 0
    }
    function print_fileinfo() {
        flag = ""
        src_file = ""
        if (old_file == "/dev/null") {
            src_file = new_file
            sub(/b\//, "", src_file)
            flag = "+"
        } else if (new_file == "/dev/null") {
            src_file = old_file
            sub(/a\//, "", src_file)
            flag = "-"
        } else {
            if (length(old_file) < length(new_file)) {
                src_file = old_file
            } else {
                src_file = new_file
            }
            sub(/b\//, "", src_file)
            flag = "*"
        }
        if (src_file != "") {
            printf(" %s %s (-%d,+%d)\n", flag, src_file, dels, adds);
            files++
            insertions += adds
            deletions += dels
        }
    }
    # main body
    {
        if ($1 ~ /^---$/) {
            print_fileinfo()
            old_file = $2
            new_file = ""
        } else if ($1 ~ /^+++$/) {
            new_file = $2
            dels = adds = 0
        } else if (old_file != "" && new_file != "") {
            if ($1 ~ /^-/ && $1 !~ /^--/) {
                dels++
            } else if ($1 ~ /^+/) {
                adds++
            }
        }
    }
    END {
        print_fileinfo()
        if (files > 0) {
            f_str = (files > 1) ? "files" : "file"
            i_str = (insertions > 1) ? "insertions" : "insertion"
            d_str = (deletions > 1) ? "deletions" : "deletion"
            if (insertions > 0) {
                if (deletions > 0) {
                    printf(" %d %s changed, %d %s(+), %d %s(-)\n", files, f_str, insertions, i_str, deletions, d_str)
                } else {
                    printf(" %d %s changed, %d %s(+)\n", files, f_str, insertions, i_str)
                }
            } else {
                printf(" %d %s changed, %d %s(-)\n", files, f_str, deletions, d_str)
            }
        }
    }' "$1"
}

# patch_stat PATCH
patch_stat() {
    local pf=$1
    if [ ! -f "$pf" ]; then
        return -1
    fi
    local stat=$(git apply --stat "$pf")
    if [ -z "$stat" ]; then
        stat=$(__patch_stat "$pf")
        if [ -z "$stat" ]; then
            stat=$(sed -e '1,/^---$/d' -e '/^$/,$d' "$pf")
        fi
    fi
    echo "$stat"
}
